今天來講一下request跟取得secret
先在資料夾中創建一個handler的資料夾,在裡面創建一個httpClient.go的檔案
這邊先上code
handler/httpClient.go
package handler
import (
	"bytes"
	"net/http"
	"github.com/swaggo/swag/example/celler/model"
)
type Client struct {
	httpClient *http.Client
}
func NewClient() *Client {
	return &Client{
		httpClient: &http.Client{},
	}
}
// SendRequest 通用的 HTTP 請求方法
func (c *Client) SendRequest(req model.Request) (*http.Response, error) {
	// 在此處實現請求的發送邏輯,並返回響應
	// 可以在這裡處理例如設置請求頭、處理請求錯誤等等
	// 這個方法可以支持不同的 HTTP 方法
	httpRequest, err := http.NewRequest(req.Method, req.URL, bytes.NewBuffer(req.Body))
	if err != nil {
		return nil, err
	}
	// 設置請求頭
	for key, value := range req.Headers {
		httpRequest.Header.Set(key, value)
	}
	// 發送請求
	response, err := c.httpClient.Do(httpRequest)
	if err != nil {
		return nil, err
	}
	return response, nil
}
// Get 方法用於發送 GET 請求
func (c *Client) Get(url string, headers map[string]string) (*http.Response, error) {
	req := model.Request{
		URL:     url,
		Method:  "GET",
		Headers: headers,
	}
	return c.SendRequest(req)
}
// Post 方法用於發送 POST 請求
func (c *Client) Post(url string, headers map[string]string, body []byte) (*http.Response, error) {
	req := model.Request{
		URL:     url,
		Method:  "POST",
		Headers: headers,
		Body:    body,
	}
	return c.SendRequest(req)
}
// Put 方法用於發送 PUT 請求
func (c *Client) Put(url string, headers map[string]string, body []byte) (*http.Response, error) {
	req := model.Request{
		URL:     url,
		Method:  "PUT",
		Headers: headers,
		Body:    body,
	}
	return c.SendRequest(req)
}
// Patch 方法用於發送 PATCH 請求
func (c *Client) Patch(url string, headers map[string]string, body []byte) (*http.Response, error) {
	req := model.Request{
		URL:     url,
		Method:  "PATCH",
		Headers: headers,
		Body:    body,
	}
	return c.SendRequest(req)
}
SendRequest這一個func會幫忙處理好url、request method以及Body,然後才會去處理Header的部分,當Header設定好後會將request送出,並且取得response,而這個function可以給任何的http request使用
不同方法如下面的function所示,只要填入對應的內容就可以自動送出http request。
至於在main.go中使用之前,記得要先下go mod tidy來整理引用的module
一樣在root目錄中創建一個資料夾,這邊叫做config,並且在裡面創建一個json檔,叫做secret.json
然後我會把我的secret丟在這個json裏面
config/secret.json
{
    "Authorization":  "Bearer [your secret]"
}
然後在controller/notion.go這一個controller中加上viper這個module
go get github.com/spf13/viper
controller/notion.go
import (
	...
	"github.com/spf13/viper"
)
func (c *Controller) CreateNotionDatabase(ctx *gin.Context) {
	viper.AddConfigPath("./config") // config所在的目錄路徑
	viper.SetConfigName("secret")
	err := viper.ReadInConfig()
	if err != nil {
		log.Fatalln(err)
	}
	auth := viper.Get("Authorization")
	client := handler.NewClient()
	header := map[string]string{
		"Authorization":  auth.(string),
		"Notion-Version": "2022-06-28",
		"Content-Type":   "application/json",
	}
  ...
}
這邊要先設定viper的目錄,這邊是用相對目錄
然後SetConfigName的部分就打上secret,這邊viper會自動處理副檔名,他支援的格式有這些
確定讀取Config沒有報錯後
用viper.Get("Authorization")來取得auth的secret,這樣就不用直接把secret打在code中了
並且可以在.gitignore中設定secert.json不放入github中,就不用擔心把secret上傳了